<!-- components/inventory/ProductFormDialog.vue -->
<template>
  <el-dialog
    v-model="visible"
    :title="mode === 'create' ? '新增产品' : '编辑产品'"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      v-loading="submitting"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="SKU" prop="sku">
            <el-input 
              v-model="form.sku" 
              placeholder="请输入SKU"
              :disabled="mode === 'edit'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品名称" prop="name">
            <el-input 
              v-model="form.name" 
              placeholder="请输入产品名称"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="类目" prop="categoryId">
            <el-cascader
              v-model="form.categoryId"
              :options="categoryOptions"
              :props="cascaderProps"
              placeholder="请选择类目"
              clearable
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品牌" prop="brandId">
            <el-select 
              v-model="form.brandId" 
              placeholder="请选择品牌"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="brand in brandOptions"
                :key="brand.id"
                :label="brand.name"
                :value="brand.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规格">
            <el-input 
              v-model="form.specification" 
              placeholder="请输入规格"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-select 
              v-model="form.unit" 
              placeholder="请选择单位"
              clearable
              style="width: 100%"
            >
              <el-option label="个" value="个" />
              <el-option label="件" value="件" />
              <el-option label="箱" value="箱" />
              <el-option label="套" value="套" />
              <el-option label="台" value="台" />
              <el-option label="千克" value="千克" />
              <el-option label="米" value="米" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="售价" prop="salePrice">
            <el-input-number 
              v-model="form.salePrice" 
              :min="0"
              :precision="2"
              :step="0.1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="成本价" prop="costPrice">
            <el-input-number 
              v-model="form.costPrice" 
              :min="0"
              :precision="2"
              :step="0.1"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="当前库存">
            <el-input-number 
              v-model="form.stock" 
              :min="0"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="安全库存">
            <el-input-number 
              v-model="form.minStock" 
              :min="0"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="状态">
        <el-radio-group v-model="form.status">
          <el-radio value="active">在售</el-radio>
          <el-radio value="inactive">下架</el-radio>
          <el-radio value="outofstock">缺货</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="描述">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入产品描述"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="submitting"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, defineProps, defineEmits, watch, onMounted } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import * as inventoryAPI from '@/api/inventory'

// 定义产品表单接口
interface ProductForm {
  id?: number
  sku: string
  name: string
  specification: string
  unit: string
  categoryId: number | null
  categoryName?: string
  brandId: number | null
  brandName?: string
  description: string
  stock: number
  minStock: number
  salePrice: number
  costPrice: number
  status: string
}

const props = defineProps<{
  modelValue: boolean
  productData: ProductForm | null
  mode: 'create' | 'edit'
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success', product: ProductForm): void
}>()

const visible = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()
const categoryOptions = ref<any[]>([])
const brandOptions = ref<inventoryAPI.Brand[]>([])

const form = ref<ProductForm>({
  sku: '',
  name: '',
  specification: '',
  unit: '',
  categoryId: null,
  brandId: null,
  description: '',
  stock: 0,
  minStock: 0,
  salePrice: 0,
  costPrice: 0,
  status: 'active'
})

const rules = ref<FormRules>({
  sku: [
    { required: true, message: '请输入SKU', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请选择单位', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择类目', trigger: 'change' }
  ],
  brandId: [
    { required: true, message: '请选择品牌', trigger: 'change' }
  ],
  salePrice: [
    { required: true, message: '请输入售价', trigger: 'blur' }
  ],
  costPrice: [
    { required: true, message: '请输入成本价', trigger: 'blur' }
  ]
})

// 级联选择器配置
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  expandTrigger: 'hover' as const,
  multiple: false
}

// 加载类目数据
const loadCategories = async () => {
  try {
    const response = await inventoryAPI.getProductCategories()
    // 确保数据是数组格式
    categoryOptions.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    console.error('加载产品类目失败:', error)
    categoryOptions.value = []
  }
}

// 加载品牌数据
const loadBrands = async () => {
  try {
    const response = await inventoryAPI.getBrands()
    // 确保数据是数组格式
    brandOptions.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    console.error('加载品牌数据失败:', error)
    brandOptions.value = []
  }
}

// 监听modelValue变化
watch(() => props.modelValue, (newValue: boolean) => {
  visible.value = newValue
  if (newValue && props.productData) {
    // 编辑模式下填充表单数据，并确保数值类型正确
    form.value = {
      ...props.productData,
      stock: Number(props.productData.stock) || 0,
      minStock: Number(props.productData.minStock) || 0,
      salePrice: Number(props.productData.salePrice) || 0,
      costPrice: Number(props.productData.costPrice) || 0
    }
  } else if (newValue) {
    // 新增模式下重置表单
    resetForm()
  }
})

// 监听visible变化
watch(visible, (newValue: boolean) => {
  emit('update:modelValue', newValue)
})

const resetForm = () => {
  form.value = {
    sku: '',
    name: '',
    specification: '',
    unit: '',
    categoryId: null,
    brandId: null,
    description: '',
    stock: 0,
    minStock: 0,
    salePrice: 0,
    costPrice: 0,
    status: 'active'
  }
}

const handleClose = () => {
  visible.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      submitForm()
    }
  })
}

const submitForm = async () => {
  submitting.value = true
  try {
    // 创建一个符合API要求的对象，并确保数值类型正确
    const productData = {
      ...form.value,
      categoryId: form.value.categoryId,
      brandId: form.value.brandId,
      stock: Number(form.value.stock) || 0,
      minStock: Number(form.value.minStock) || 0,
      salePrice: Number(form.value.salePrice) || 0,
      costPrice: Number(form.value.costPrice) || 0
    }
    
    if (props.mode === 'create') {
      // 创建产品
      await inventoryAPI.createProduct(productData)
      ElMessage.success('产品添加成功')
    } else {
      // 更新产品
      if (form.value.id) {
        await inventoryAPI.updateProduct(form.value.id, productData)
        ElMessage.success('产品更新成功')
      }
    }
    
    emit('success', { ...form.value })
    handleClose()
  } catch (error) {
    ElMessage.error('操作失败: ' + (error as Error).message)
  } finally {
    submitting.value = false
  }
}

// 组件挂载时加载类目和品牌数据
onMounted(() => {
  loadCategories()
  loadBrands()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>